package com.wolfking.web.ssoauth.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Maps;
import com.wolfking.back.core.annotation.ssoauth.Sign;
import com.wolfking.back.core.bean.Dict;
import com.wolfking.back.core.bean.Office;
import com.wolfking.back.core.bean.PageInfo;
import com.wolfking.back.core.bean.Role;
import com.wolfking.back.core.bean.User;
import com.wolfking.back.core.config.SsoConfig;
import com.wolfking.back.core.feignclient.DictFeignClient;
import com.wolfking.back.core.feignclient.MenuFeignClient;
import com.wolfking.back.core.feignclient.OfficeFeignClient;
import com.wolfking.back.core.feignclient.RoleFeignClient;
import com.wolfking.back.core.feignclient.UserFeignClient;
import com.wolfking.back.core.util.DataEntityUtil;

import jersey.repackaged.com.google.common.collect.Lists;

/**
 * 角色的controller
 * <P>
 * 字典的增删查改
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月26日下午1:09:59
 * @版权 归wolfking所有
 */
@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	private DictFeignClient dictFeignClient;

	@Autowired
	private SsoConfig ssoConfig;

	@Autowired
	private RoleFeignClient roleFeignClient;

	@Autowired
	private OfficeFeignClient officeFeignClient;

	@Autowired
	private MenuFeignClient menuFeignClient;

	@Autowired
	private UserFeignClient userFeignClient;

	/**
	 * 字典的列表页，包括模糊查询
	 * <p>
	 * 
	 * @param model
	 * @param dict
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
	public String list(Model model, Role role, @RequestParam(defaultValue = "1") int pageNum,
			@RequestParam(defaultValue = "10") int pageSize) {
		PageInfo<Role> page = roleFeignClient.pageRole(role, pageNum, pageSize).getBody();
		List<Dict> dicts = dictFeignClient.getByType("sys_data_scope").getBody();
		model.addAttribute("page", page);
		Map<String, String> dictMap = Maps.newHashMap();
		for (Dict dict : dicts)
			dictMap.put(dict.getValue(), dict.getLabel());
		model.addAttribute("dictMap", dictMap);
		model.addAttribute("role", role);
		Map<String, String> officeMap = Maps.newHashMap();
		List<Office> offices = officeFeignClient.getAllOffice().getBody();
		for (Office office : offices)
			officeMap.put(office.getId(), office.getName());
		model.addAttribute("officeMap", officeMap);
		return "role/list";
	}

	/**
	 * 验证角色名是否有效
	 * 
	 * @param oldName
	 * @param name
	 * @return
	 */
	@Sign
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldName, String name) {
		Role role = new Role();
		role.setName(name);
		if (name != null && name.equals(oldName)) {
			return "true";
		} else if (name != null) {
			List<Role> list = roleFeignClient.selectAccuracy(role).getBody();
			if (list == null || list.size() == 0)
				return "true";
		}
		return "false";
	}

	/**
	 * 验证角色英文名是否有效
	 * 
	 * @param oldName
	 * @param name
	 * @return
	 */
	@Sign
	@ResponseBody
	@RequestMapping(value = "/checkEnname")
	public String checkEnname(String oldEnname, String enname) {
		Role role = new Role();
		role.setEnname(enname);
		if (enname != null && enname.equals(oldEnname)) {
			return "true";
		} else if (enname != null) {
			List<Role> list = roleFeignClient.selectAccuracy(role).getBody();
			if (list == null || list.size() == 0)
				return "true";
		}
		return "false";
	}

	@Sign
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String editGet(Model model, Role role) {
		if (StringUtils.isNotEmpty(role.getId()))
			role = roleFeignClient.getRole(role.getId()).getBody();
		model.addAttribute("role", role);
		List<Dict> dicts = dictFeignClient.getByType("sys_data_scope").getBody();
		model.addAttribute("dicts", dicts);
		model.addAttribute("menuList", menuFeignClient.getAllMenu().getBody());
		model.addAttribute("officeList", officeFeignClient.getAllOffice().getBody());
		Office office = new Office();
		if (StringUtils.isNotEmpty(role.getOfficeId()))
			office = officeFeignClient.getOffice(role.getOfficeId()).getBody();
		model.addAttribute("office", office);
		return "role/edit";
	}

	@Sign
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String editPost(RedirectAttributes redirectAttributes, Role role, User user) {
		DataEntityUtil.assemblyDataEntity(role, user);
		if (StringUtils.isEmpty(role.getId())) {
			roleFeignClient.addRole(role);
			redirectAttributes.addFlashAttribute("message", "添加角色成功");
		} else {
			roleFeignClient.updateRole(role);
			redirectAttributes.addFlashAttribute("message", "修改角色成功");
		}
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/role/list";
	}

	@Sign
	@RequestMapping(value = "/assign", method = RequestMethod.GET)
	public String assignGet(@RequestParam String id, Model model) {
		Role role = roleFeignClient.getRole(id).getBody();
		Office office = new Office();
		Map<String, String> dictMap = Maps.newHashMap();
		List<Dict> dicts = dictFeignClient.getByType("sys_data_scope").getBody();
		for (Dict dict : dicts)
			dictMap.put(dict.getValue(), dict.getLabel());
		if (StringUtils.isNotEmpty(role.getOfficeId()))
			office = officeFeignClient.getOffice(role.getOfficeId()).getBody();
		Map<String, String> officeMap = Maps.newHashMap();
		List<Office> offices = officeFeignClient.getAllOffice().getBody();
		for (Office o : offices)
			officeMap.put(o.getId(), o.getName());
		List<User> userList = userFeignClient.getUserListByRoleId(id).getBody();
		if (userList == null)
			userList = Lists.newArrayList();
		model.addAttribute("role", role);
		model.addAttribute("office", office);
		model.addAttribute("dictMap", dictMap);
		model.addAttribute("userList", userList);
		model.addAttribute("officeMap", officeMap);
		return "role/assign";
	}

	/**
	 * 删除角色
	 * 
	 * @param id
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public String delete(@RequestParam String id) {
		if (StringUtils.isNotBlank(id))
			roleFeignClient.deleteRole(id);
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/role/list";
	}

	/**
	 * 移除角色
	 * 
	 * @param userId
	 * @param roleId
	 * @param redirectAttributes
	 * @param current
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/outrole", method = RequestMethod.GET)
	public String outrole(@RequestParam String userId, @RequestParam String roleId,
			RedirectAttributes redirectAttributes, User current) {

		Role role = roleFeignClient.getRole(roleId).getBody();
		User user = userFeignClient.getUser(userId).getBody();
		if (current.getId().equals(userId)) {
			redirectAttributes.addFlashAttribute("message",
					"无法从角色【" + role.getName() + "】中移除用户【" + user.getName() + "】自己！");
			redirectAttributes.addFlashAttribute("messageType", "warning");
		} else {
			roleFeignClient.outrole(roleId, userId);
			redirectAttributes.addFlashAttribute("message",
					"用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除成功！");
		}
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/role/assign?id=" + roleId;
	}

	@Sign
	@RequestMapping(value = "/user2role", method = RequestMethod.POST)
	public String user2role(Model model, @RequestParam String roleId) {
		Role role = roleFeignClient.getRole(roleId).getBody();
		List<User> userList = userFeignClient.getUserListByRoleId(roleId).getBody();
		if (userList == null)
			userList = Lists.newArrayList();
		String selectIds = "";
		for (User user : userList)
			selectIds += "," + user.getId();
		if (StringUtils.isNotEmpty(selectIds))
			selectIds = selectIds.substring(1);
		model.addAttribute("role", role);
		model.addAttribute("userList", userList);
		model.addAttribute("selectIds", selectIds);
		model.addAttribute("officeList", officeFeignClient.getAllOffice().getBody());
		return "role/user2role";
	}

	@Sign
	@ResponseBody
	@RequestMapping(value = "/users")
	public List<Map<String, Object>> users(@RequestParam String officeId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		User user = new User();
		user.setOfficeId(officeId);
		List<User> list = userFeignClient.seleteAccuracy(user).getBody();
		for (User e : list) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", 0);
			map.put("name", e.getName());
			mapList.add(map);
		}
		return mapList;
	}

	@Sign
	@RequestMapping(value = "/assignrole", method = RequestMethod.POST)
	public String assignRole(Role role, String[] idsArr, RedirectAttributes redirectAttributes) {
		role = roleFeignClient.getRole(role.getId()).getBody();
		StringBuilder msg = new StringBuilder();
		int newNum = 0;
		for (int i = 0; i < idsArr.length; i++) {
			User user = roleFeignClient.assginrole(role.getId(), idsArr[i]).getBody();
			if (null != user) {
				msg.append("<br/>新增用户【" + user.getName() + "】到角色【" + role.getName() + "】！");
				newNum++;
			}
		}
		redirectAttributes.addFlashAttribute("message", "已成功分配 " + newNum + " 个用户" + msg);
		return "redirect:/role/assign?id=" + role.getId();
	}
}
